package client;

import java.io.BufferedReader;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.URL;
import java.util.Vector;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;


import java.net.Proxy;

	public class ChatGPT {
		private String jsonInput1 = "{\"model\": \"gpt-3.5-turbo\", \"messages\": [";
		private Vector<String> jsonInput2;
		private String jsonInput3 = "]}";
		
		public ChatGPT() {
			// TODO Auto-generated constructor stub
			jsonInput2 = new Vector<>();
		}
		
		public void setUserPrompt(String msg) {
			String prompt = "{\"role\": \"user\", \"content\": \"" + msg + "\"}";
			System.out.println(prompt);
			jsonInput2.add(prompt);
		}
		
		public void setAssitantPrompt(String msg) {
			String prompt = "{\"role\": \"assistant\", \"content\": \"" + msg + "\"}";
			System.out.println(prompt);
			jsonInput2.add(prompt);
		}
		
	    public String chat() {
	        String apiKey = "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";
	        String apiUrl =  "https://api.openai.com/v1/chat/completions";
	        Proxy proxy = new Proxy(Proxy.Type.HTTP,new InetSocketAddress("127.0.0.1",7890));
	        String replyContent = "";
	        try {
	            URL url = new URL(apiUrl);
	            HttpURLConnection connection = (HttpURLConnection) url.openConnection(proxy);
	            connection.setRequestMethod("POST");
	            connection.setRequestProperty("Authorization", "Bearer " + apiKey);
	            connection.setRequestProperty("Content-Type", "application/json");
	            connection.setDoOutput(true);

	            String jsonInput = jsonInput1;
	            for(int i = 0; i < jsonInput2.size() - 1; i++) {
	            	jsonInput += jsonInput2.elementAt(i) + ", ";
	            }
	            jsonInput += jsonInput2.lastElement();
	            jsonInput += jsonInput3;
	            
	            System.out.println(jsonInput);
	            
	            OutputStream outputStream = connection.getOutputStream();
	            outputStream.write(jsonInput.getBytes());
	            outputStream.flush();

	            // 设置请求参数和数据
	            // ...

	            // 发送请求
	            int responseCode = connection.getResponseCode();
	            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
	            String line;
	            StringBuilder response = new StringBuilder();

	            while ((line = reader.readLine()) != null) {
	                response.append(line);
	            }
	            reader.close();

	            // 处理响应
	            if (responseCode == HttpURLConnection.HTTP_OK) {
	                // 解析响应数据
	                // ...
	            	// 创建 Gson 实例
	            	Gson gson = new Gson();
	            	
	            	JsonElement jsonElement = gson.fromJson(response.toString(), JsonElement.class);

	            	// 将 JsonElement 转换为 JsonObject
	            	JsonObject jsonResponse = jsonElement.getAsJsonObject();

	            	// 提取回复信息
	            	JsonArray choicesArray = jsonResponse.getAsJsonArray("choices");
	            	JsonObject firstChoice = choicesArray.get(0).getAsJsonObject();
	            	JsonObject message = firstChoice.getAsJsonObject("message");
	            	replyContent = message.get("content").getAsString();

	            	setAssitantPrompt(replyContent);
	            } else {
	                
	            }
	        } catch (IOException e) {
	            e.printStackTrace();
	        }         	// 将 response 转换为 JsonElement
	        
	        // 在解析响应数据后，调用回调函数处理 API 回复
	        return replyContent;
	    }
	}
